package com.ryujung.binary_tree.leetCode_98;


import java.util.Deque;
import java.util.LinkedList;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    /**
     * 尝试中序遍历的方式解题
     * <p>
     * 中序遍历：左子树、根节点、右子树
     *
     * BST的中序遍历结果一定是有序的，根据这个特点进行遍历并判断即可
     */
    public boolean isValidBST2(TreeNode root) {
        if (root == null) return true;

        Deque<TreeNode> stk = new LinkedList<>();
        long preVal = Long.MIN_VALUE;
        while (root != null || !stk.isEmpty()) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            if (root.val <= preVal) {
                return false;
            }
            preVal = root.val;
            root = root.right;
        }
        return true;
    }

    /**
     * 改良两个辅助函数的写法，
     * 即每次递归，需要另外传递一个最大值和最小值
     */
    public boolean isValidBST1(TreeNode root) {
        return isValidHelper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidHelper(TreeNode root, long min, long max) {
        if (root == null) return true;

        boolean res = root.val > min && root.val < max;

        res &= isValidHelper(root.left, min, root.val) &&
                isValidHelper(root.right, root.val, max);
        return res;
    }
    // 时间复杂度: O(n)
    // 空间复杂度: O(n)


    /**
     * 二叉搜索树：
     * 左右子树必须也是BST （递归）
     * 左子树小于root，右子树大于root
     * <p>
     * 思路：
     * 写两个辅助函数，计算TreeNode中的最大值和最小值
     * 然后递归判断每个节点： max(left) < root.val, min(right) > root.val
     * 否则结果为false
     */
    public boolean isValidBST11(TreeNode root) {
        if (root == null) return true;

        if (root.left != null && max(root.left) >= root.val) {
            return false;
        }
        if (root.right != null && min(root.right) <= root.val) {
            return false;
        }
        return isValidBST11(root.left) && isValidBST11(root.right);
    }

    public int max(TreeNode node) {
        if (node == null) return -1;
        int max = node.val;
        if (node.left != null) {
            max = Math.max(max, max(node.left));
        }
        if (node.right != null) {
            max = Math.max(max, max(node.right));
        }
        return max;
    }

    public int min(TreeNode node) {
        if (node == null) return -1;
        int min = node.val;
        if (node.left != null) {
            min = Math.min(min, min(node.left));
        }
        if (node.right != null) {
            min = Math.min(min, min(node.right));
        }
        return min;
    }
}